// pages/cart/cart.js
import {
  showToast,wx_payment
} from '../../utils/asyncWx.js'
import regeneratorRuntime from '../../lib/runtime/runtime'
import{createOrder,rePay,order_status}from '../../service/order_user'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  //监听页面显示
  onShow: function () {
    let pages=getCurrentPages()
    let currentPage=pages[pages.length-2]
   if(currentPage.route=='pages/goods_detail/goods_detail'){
     //从缓存中取出收货地址
     const address = wx.getStorageSync('address')
     //从缓存中取出购物车商品信息
     let cart = wx.getStorageSync('imCart')
     //计算商品价格和数量
     let totalPrice = 0;
     let totalNum = cart.length
     cart.forEach(v => {
       totalPrice = v.goods_price 
     })
     //把购物车数组再次填充回data和缓存中
     this.setData({
      cart,
      totalPrice,
      totalNum,
      address
    })
   }else{
     //从缓存中取出收货地址
     const address = wx.getStorageSync('address')
     //从缓存中取出购物车商品信息
     let cart = wx.getStorageSync('cart') || []
     cart=cart.filter(v=>v.checked)
     
     //计算商品价格和数量
     let totalPrice = 0;
     let totalNum = 0
     cart.forEach(v => {
       totalPrice += v.goods_price * v.num
       totalNum += v.num
     })
     
     //把购物车数组再次填充回data和缓存中
     this.setData({
       cart,
       totalPrice,
       totalNum,
       address
     })
   }
   
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  //----------监听点击事件----------
  //监听点击结算
  async handleOrderPay(){
    try {
      // p判断缓存是否有token
    const token=wx.getStorageSync('token')
    if(!token){
      wx.navigateTo({
        url: '/pages/auth/auth',
      })
    }
    //3.创建订单
    //准备请求体参数
    const order_price=this.data.totalPrice;
    const consignee_addr=this.data.address.all;
    const cart=this.data.cart;
    let goods=[];
    cart.forEach(v=>goods.push({
      good_id:v.goods_id,
      goods_number:v.num,
      goods_price:v.goods_price
    }))

    //4.准备发送请求
    //4.1 整合请求参数
    const orderParams={order_price,consignee_addr,goods}
    const {order_number}=await createOrder({data:orderParams,method:"post"})
    //5.请求预支付接口
    const {pay}=await rePay({data:{order_number},method:"post"})
    //6.发送微信支付
    await wx_payment(pay)
    //7.查询后台 订单状态
    await order_status({data:{order_number},method:"post"})
    await showToast({title:"支付成功"})
    //8.手动删除缓存中的已支付商品，并重新保存
    let newCart=wx.getStorageSync('cart')
    newCart=newCart.filter(v=>!v.checked)
    wx.setStorageSync('cart', newCart)
    //9.支付成功跳转到订单页面
    wx.navigateTo({
      url: '/pages/order/order',
    })
    } catch (error) {
      await showToast({title:"支付失败"})
    }
  },


})

